package yt.kpool.fragment;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import yt.kpool.R;
import yt.kpool.activity.home.PowAc;
import yt.kpool.activity.setting.ProfitTypeActivity;
import yt.kpool.adapter.PersonSelectListviewAdapter;
import yt.kpool.adapter.ProfitAdapter;
import yt.kpool.adapter.ProfitBtcAdapter;
import yt.kpool.bean.BtcProfitBean;
import yt.kpool.bean.CurrencyList;
import yt.kpool.bean.MinerBean;
import yt.kpool.bean.PoolAccountInfoBean;
import yt.kpool.bean.ProfitBean;
import yt.kpool.interfac.Observer;
import yt.kpool.interfac.OnSelectPersonListener;
import yt.kpool.network.HttpUtils;
import yt.kpool.network.MyGson;
import yt.kpool.network.NetHelperNew;
import yt.kpool.util.NetWorkUtil;
import yt.kpool.util.ToastUtil;
import yt.kpool.util.Util;
import yt.kpool.util.imageUtil.GlideUtil;
import yt.kpool.view.dialog.ErrorDialog;
import yt.kpool.view.dialog.LoadingDialog;
import yt.kpool.view.lazyviewpager.LazyFragmentPagerAdapter;
import yt.kpool.view.pop.CurrencyPopupWindow;

import static yt.kpool.util.Util.showSnackBar;

/**
 * 收益
 */
public class ProfitFragment extends Fragment implements LazyFragmentPagerAdapter.Laziable, Observer {
    @BindView(R.id.tv_person)
    TextView tv_person;
    //    @BindView(R.id.tv_money)
//    NumberRunningTextView tvMoney;
    @BindView(R.id.tv_moneys)
    TextView tvMoneys;
    @BindView(R.id.tv_moneyc)
    TextView tvMoneyc;
    @BindView(R.id.drawer_layout)
    RelativeLayout drawer_layout;
    @BindView(R.id.ly_coinkind)
    LinearLayout ly_coinkind;
    @BindView(R.id.iv_coin)
    ImageView iv_curreney;
    @BindView(R.id.tv_name)
    TextView tv_currrncyname;
    @BindView(R.id.recycler)
    LRecyclerView mRecyclerView;
    @BindView(R.id.recycler2)
    LRecyclerView mRecyclerView2;
    @BindView(R.id.tv_sl)
    TextView tv_sl;
    @BindView(R.id.tv_slc)
    TextView tv_slc;
    @BindView(R.id.tv_pay)
    TextView tv_pay;
    @BindView(R.id.tv_payc)
    TextView tv_payc;
    @BindView(R.id.tv_ye)
    TextView tv_ye;
    @BindView(R.id.tv_yec)
    TextView tv_yec;
    @BindView(R.id.iv_account)
    ImageView iv_account;
    @BindView(R.id.ll_1)
    LinearLayout ll_1;
    @BindView(R.id.ll_2)
    LinearLayout ll_2;

    @BindView(R.id.tv_profit_type)
    TextView tv_profit_type;//结算模式

    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private LRecyclerViewAdapter lRecyclerViewAdapter2;
    private OnSelectPersonListener onSelectPersonListener;// 挖币账户选择
    private int currencyId;//币种id
    private List<CurrencyList.DataBean> currencyListData;
    private ProfitAdapter profitAdapter;
    private ProfitBtcAdapter profitBtcAdapter;//btc币种专用
    private CurrencyPopupWindow currencyPopupWindow;//币种选择
    private int childaccountId;
    private LoadingDialog loadingDialog;
    private List<ProfitBean.DataBean> list_profit = new ArrayList<>();
    private List<BtcProfitBean.DataBean.ProfitListBean> list_profit_btc = new ArrayList<>();
    private int pagenum = 1;//页数
    private boolean isfirst = false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fg_profit, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = false, priority = 0)
    public void handleData(String str) {
        Log.i("-->", "================" + str);
        if (isfirst) {
            if (str.equals("456")) {
                pagenum = 1;
                list_profit.clear();
                list_profit_btc.clear();
                getData(pagenum);
                getAccountMessage();
            }
        }

        isfirst = true;

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initView2() {
        mRecyclerView2.setLayoutManager(new LinearLayoutManager(getContext()));
        profitBtcAdapter = new ProfitBtcAdapter(getActivity(), list_profit_btc);
        lRecyclerViewAdapter2 = new LRecyclerViewAdapter(profitBtcAdapter);
        mRecyclerView2.setAdapter(lRecyclerViewAdapter2);
        mRecyclerView2.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader); //设置下拉刷新Progress的样式
        // mRecyclerView.setArrowImageView(R.drawable.iconfont_downgrey);  //设置下拉刷新箭头
        //设置头部加载颜色
        mRecyclerView2.setHeaderViewColor(R.color.system_color, R.color.system_color, android.R.color.white);
//设置底部加载颜色
        mRecyclerView2.setFooterViewColor(R.color.system_color, R.color.system_color, android.R.color.white);

        //分割线
        DividerDecoration divider = new DividerDecoration.Builder(getActivity())
                .setHeight(R.dimen.d_0)
                .setPadding(R.dimen.d_18)
                .setColorResource(R.color.line)
                .build();
        mRecyclerView2.addItemDecoration(divider);
        mRecyclerView2.setOnRefreshListener(new OnRefreshListener() {//下拉刷新
            @Override
            public void onRefresh() {
                pagenum = 1;
                list_profit_btc.clear();
                profitBtcAdapter.setDw(tv_currrncyname.getText().toString().toUpperCase());
                profitBtcAdapter.notifyDataSetChanged();
                getData(pagenum);
            }
        });
        mRecyclerView2.setPullRefreshEnabled(false);
        mRecyclerView2.setOnLoadMoreListener(new OnLoadMoreListener() {//加载更多
            @Override
            public void onLoadMore() {
                getData(pagenum);
            }
        });
    }

    private void initView() {
        EventBus.getDefault().register(this);

        loadingDialog = new LoadingDialog(getActivity(), 0);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        profitAdapter = new ProfitAdapter(getActivity(), list_profit);
        lRecyclerViewAdapter = new LRecyclerViewAdapter(profitAdapter);
        mRecyclerView.setAdapter(lRecyclerViewAdapter);
        mRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader); //设置下拉刷新Progress的样式
        // mRecyclerView.setArrowImageView(R.drawable.iconfont_downgrey);  //设置下拉刷新箭头
        //设置头部加载颜色
        mRecyclerView.setHeaderViewColor(R.color.system_color, R.color.system_color, android.R.color.white);
//设置底部加载颜色
        mRecyclerView.setFooterViewColor(R.color.system_color, R.color.system_color, android.R.color.white);

        //分割线
        DividerDecoration divider = new DividerDecoration.Builder(getActivity())
                .setHeight(R.dimen.d_05)
                .setPadding(R.dimen.d_18)
                .setColorResource(R.color.line)
                .build();
        mRecyclerView.addItemDecoration(divider);
        mRecyclerView.setOnRefreshListener(new OnRefreshListener() {//下拉刷新
            @Override
            public void onRefresh() {
                pagenum = 1;
                list_profit.clear();
                profitAdapter.setDw(tv_currrncyname.getText().toString().toUpperCase());
                profitAdapter.notifyDataSetChanged();
                getData(pagenum);
            }
        });
        mRecyclerView.setPullRefreshEnabled(false);
        mRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {//加载更多
            @Override
            public void onLoadMore() {
                getData(pagenum);
            }
        });
    }

    /**
     * 币种选择pop初始化
     */
    private void initCurrencyPopupWindow() {
        currencyPopupWindow = new CurrencyPopupWindow(currencyListData, getActivity(), new CurrencyPopupWindow.OnSeleCurrencyLayoutListener() {
            @Override
            public void selectHouseLayout(int i) {
                currencyId = currencyListData.get(i).getId();
                GlideUtil.loadImage(getActivity(), NetHelperNew.URL + currencyListData.get(i).getIcon(), iv_curreney, R.mipmap.failimage, R.mipmap.failimage);
                tv_currrncyname.setText(currencyListData.get(i).getCode().toUpperCase());
                onSelectPersonListener.selectCurrency(currencyId);
                pagenum = 1;

                if ("BTC".equals(tv_currrncyname.getText().toString())) {
                    ll_1.setVisibility(View.GONE);
                    ll_2.setVisibility(View.VISIBLE);
                    list_profit_btc.clear();
                    profitBtcAdapter.setDw(tv_currrncyname.getText().toString().toUpperCase());
                    profitBtcAdapter.notifyDataSetChanged();
                } else {
                    ll_2.setVisibility(View.GONE);
                    ll_1.setVisibility(View.VISIBLE);
                    list_profit.clear();
                    profitAdapter.setDw(tv_currrncyname.getText().toString().toUpperCase());
                    profitAdapter.notifyDataSetChanged();
                }
                getData(pagenum);
                getAccountMessage();
            }
        });
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initView2();
        if (NetWorkUtil.checkNet(getActivity())) {
            getCurrrencyData();
        } else {

            ToastUtil.showToast(getActivity(), getResources().getString(R.string.internet_error));
        }


        childaccountId = onSelectPersonListener.childAccountId();

        currencyId = onSelectPersonListener.getCurrencyId();

        if (onSelectPersonListener.getIsFastLogin()) {
            iv_account.setImageDrawable(getActivity().getResources().getDrawable(R.mipmap.daohang2));
            tv_person.setText(onSelectPersonListener.childAccountName() + " （只读页面）");
        } else {
            iv_account.setImageDrawable(getActivity().getResources().getDrawable(R.mipmap.daohang));
            tv_person.setText(onSelectPersonListener.childAccountName());
        }
    }

    /**
     * 获取币种数据
     */
    private void getCurrrencyData() {
        currencyListData = new ArrayList<>();
        if (NetWorkUtil.check(getActivity())) {
            loadingDialog.show();

            NetHelperNew.GetCurrencyList(new HttpUtils.HttpCallback() {
                @Override
                public void onSuccess(String data) {
                    loadingDialog.dismiss();
                    Log.i("-->", "币种列表：" + data);
                    CurrencyList currencyList = MyGson.getInstance().fromJson(data, CurrencyList.class);
                    if (currencyList.getType() == 1) {

                        currencyListData.addAll(currencyList.getData());
                        initCurrencyPopupWindow();
                        if (currencyList.getData().size() > 0) {
                            if (currencyId == 0) {
                                GlideUtil.loadImage(getActivity(), NetHelperNew.URL + currencyList.getData().get(0).getIcon(), iv_curreney, R.mipmap.failimage, R.mipmap.failimage);
                                tv_currrncyname.setText(currencyList.getData().get(0).getCode().toUpperCase());
                                currencyId = currencyList.getData().get(0).getId();
                                onSelectPersonListener.selectCurrency(currencyId);
                            } else {

                                for (int i = 0; i < currencyList.getData().size(); i++) {
                                    if (currencyId == currencyList.getData().get(i).getId()) {
                                        GlideUtil.loadImage(getActivity(), NetHelperNew.URL + currencyList.getData().get(i).getIcon(), iv_curreney, R.mipmap.failimage, R.mipmap.failimage);
                                        tv_currrncyname.setText(currencyList.getData().get(i).getCode().toUpperCase());
                                    }
                                }
                            }
                            if ("BTC".equals(tv_currrncyname.getText().toString())) {
                                ll_1.setVisibility(View.GONE);
                                ll_2.setVisibility(View.VISIBLE);
                            } else {
                                ll_2.setVisibility(View.GONE);
                                ll_1.setVisibility(View.VISIBLE);
                            }
                            if (!"0".equals(childaccountId)){
                                //刷新数据
                                getData(1);
                                //获取子账号信息
                                getAccountMessage();
                                //refreshClear();
                            }

                        }

                    } else {
                        new ErrorDialog(getContext(), currencyList.getContent()).show();
                    }
                }

                @Override
                public void onError(String msg) {
                    super.onError(msg);
                    loadingDialog.dismiss();

                    ToastUtil.showToast(getActivity(), msg);
                }
            });


        }

    }

    // 当FRagmen被加载到activity的时候会被回调
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        if (activity instanceof OnSelectPersonListener) {
            onSelectPersonListener = (OnSelectPersonListener) activity; // 2.2 获取到宿主activity并赋值
        } else {
            throw new IllegalArgumentException("activity must implements FragmentInteraction");
        }
    }

    //把传递进来的activity对象释放掉
    @Override
    public void onDetach() {
        super.onDetach();
        onSelectPersonListener = null;
    }

    @OnClick({R.id.ll_menu, R.id.img_account, R.id.img_date, R.id.img_price, R.id.ly_coinkind, R.id.ll_profit_type})
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.ll_menu:
                //弹出抽屉
                onSelectPersonListener.selectPersonLayout(3, childaccountId);
                break;
            case R.id.img_account:

                Util.showSnackBar(getActivity(), "PPS挖矿收益,可能与您的实际收益存在偏差.");
                break;
            case R.id.img_date:

                Util.showSnackBar(getActivity(), "每日早上8点生成收益账单,收益账单为过去24小时的挖矿收益.");
                break;
            case R.id.img_price:

                Util.showSnackBar(getActivity(), "PPS:PPS挖矿收益.");
                break;
            case R.id.ly_coinkind:

                if (currencyPopupWindow != null)
                    currencyPopupWindow.showAsDropDown(ly_coinkind, 0, 0);
                break;
            case R.id.ll_profit_type:
                //选择分层模式
                ProfitTypeActivity.start(getActivity(),childaccountId+"",tv_person.getText().toString());
                break;
        }
    }

    @Override
    public void updatePerson(int type, String name, int id) {

        tv_person.setText(name);
        childaccountId = id;
        pagenum = 1;
        if ("BTC".equals(tv_currrncyname.getText().toString())) {

            list_profit_btc.clear();
            profitBtcAdapter.setDw(tv_currrncyname.getText().toString().toUpperCase());
            profitBtcAdapter.notifyDataSetChanged();
        } else {

            list_profit.clear();
            profitAdapter.setDw(tv_currrncyname.getText().toString().toUpperCase());
            profitAdapter.notifyDataSetChanged();
        }
        if (type == 7) {
            //收益
            getData(pagenum);
            getAccountMessage();
        }

        if (type == 3) {
            //快速登录
            tv_person.setText(name + " （只读页面）");
            iv_account.setImageDrawable(getActivity().getResources().getDrawable(R.mipmap.daohang2));
        } else {
            iv_account.setImageDrawable(getActivity().getResources().getDrawable(R.mipmap.daohang));
        }
    }

    /**
     * 修改币种
     *
     * @param img
     * @param name
     * @param id
     */
    @Override
    public void updateCurrency(int img, String name, int id) {

        currencyId = id;
        for (int i = 0; i < currencyListData.size(); i++) {
            if (currencyListData.get(i).getId() == id) {
                GlideUtil.loadImage(getActivity(), NetHelperNew.URL + currencyListData.get(i).getIcon(), iv_curreney, R.mipmap.failimage, R.mipmap.failimage);
                tv_currrncyname.setText(currencyListData.get(i).getCode().toUpperCase());
            }
        }
        // refreshClear();
        if ("BTC".equals(tv_currrncyname.getText().toString())) {
            ll_1.setVisibility(View.GONE);
            ll_2.setVisibility(View.VISIBLE);
        } else {
            ll_2.setVisibility(View.GONE);
            ll_1.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void fragmentRefresh(int type) {

    }

    /**
     * 请求收益数据
     *
     * @param pageIndex
     */
    private void getData(int pageIndex) {

        if (NetWorkUtil.check(getActivity())) {

            if ("BTC".equals(tv_currrncyname.getText().toString()) || "Btc".equals(tv_currrncyname.getText().toString())) {
                //btc收益
                NetHelperNew.BtcChildAccountProfitList(childaccountId + "", pageIndex + "", new HttpUtils.HttpCallback() {
                    @Override
                    public void onSuccess(String data) {
                        Log.i("-->", "btc收益" + data);
                        BtcProfitBean btcProfitBean = MyGson.getInstance().fromJson(data, BtcProfitBean.class);
                        if (btcProfitBean.getType() == 1) {
                            tv_profit_type.setText(btcProfitBean.getData().getProfitType());
                            if (btcProfitBean.getData().getProfitList().size() > 0) {
                                list_profit_btc.addAll(btcProfitBean.getData().getProfitList());
                                profitBtcAdapter.setDw(tv_currrncyname.getText().toString().toUpperCase());
                                profitBtcAdapter.notifyDataSetChanged();
                                pagenum++;

                            } else {
//                            Toast.makeText(getActivity(),"没有数据了~",Toast.LENGTH_SHORT).show();
                            }
                            mRecyclerView2.refreshComplete(10);
                        }

                    }

                    @Override
                    public void onError(String msg) {
                        super.onError(msg);
                        mRecyclerView2.refreshComplete(10);
                        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                    }
                });

            } else {
                //其他币种收益
                NetHelperNew.PoolProfitList(currencyId + "", childaccountId + "", pageIndex + "", new HttpUtils.HttpCallback() {
                    @Override
                    public void onSuccess(String data) {
                        ProfitBean profitBean = MyGson.getInstance().fromJson(data, ProfitBean.class);
                        if (profitBean.getType() == 1) {
                            if (profitBean.getData().size() > 0) {
                                list_profit.addAll(profitBean.getData());
                                profitAdapter.setDw(tv_currrncyname.getText().toString().toUpperCase());
                                profitAdapter.notifyDataSetChanged();
                                pagenum++;

                            } else {
//                            Toast.makeText(getActivity(),"没有数据了~",Toast.LENGTH_SHORT).show();
                            }
                            mRecyclerView.refreshComplete(10);
                        }

                    }

                    @Override
                    public void onError(String msg) {
                        super.onError(msg);
                        mRecyclerView.refreshComplete(10);
                        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                    }
                });

            }
        }

    }

    /**
     * 获取子账号信息
     */
    private void getAccountMessage() {
        //中间子帐号信息
        NetHelperNew.PoolAccountInfo("" + currencyId, "" + childaccountId, new HttpUtils.HttpCallback() {
            @Override
            public void onSuccess(String data) {
                Log.i("-->", "子帐号信息详情数据：" + data);

                PoolAccountInfoBean poolAccountInfoBean = MyGson.getInstance().fromJson(data, PoolAccountInfoBean.class);


                if (poolAccountInfoBean.getType() == 1) {
                    PoolAccountInfoBean.DataBean data1 = poolAccountInfoBean.getData();
                    String str = data1.getHashrate24H();
                    String strr[] = str.split(" ");
                    tv_sl.setText(strr[0]);
                    tv_slc.setText(strr[1]);
//                    tvMoney.setContent("0");
                    NumberFormat format = NumberFormat.getNumberInstance();
                    format.setMaximumFractionDigits(20);

                    String p = format.format(data1.getProfit()) + "";

//                    if(p.indexOf(".")!=-1)
//                    {
//
//                         int n= p.indexOf(".");
//                         int length=p.length();
//                        Log.d("ppppp",p+"/"+Integer.valueOf(p.substring(n+1,length))+"");
//                        String newp="";
//                        for (int i=0;i<p.toCharArray().length;i++)
////                        {
////                            if(p.toCharArray()[i]=='0'||p.toCharArray()[i]=='.')
////                            {
////                                newp+=p.toCharArray()[i];
////                            }
////                            else
////                            {
////                                break;
////                            }
////                        }
//                        tvMoneys.setText(newp);
//                        tvMoney.setContent(Integer.valueOf(p.substring(n+1,length))+"");
//                    }
//                    else
//                    {
//                        tvMoney.setContent(Integer.valueOf(p)+"");
//                    }
                    tvMoneys.setText(p);
                    tvMoneyc.setText(tv_currrncyname.getText().toString().toUpperCase());
                    tv_pay.setText(Util.Knumber(data1.getPayTotal()));
                    tv_pay.requestLayout();
                    tv_payc.setText(tv_currrncyname.getText().toString().toUpperCase());
                    tv_ye.setText(Util.Knumber(data1.getBalance()));
                    tv_yec.setText(tv_currrncyname.getText().toString().toUpperCase());

                }
            }

            @Override
            public void onError(String msg) {
                super.onError(msg);


                ToastUtil.showToast(getActivity(), msg);
            }
        });

    }

}